package com.enn.demo.core.domain.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.enn.demo.core.domain.shared.enums.DelFlagEnum;
import com.enn.demo.core.domain.model.person.Person;
import com.enn.demo.core.domain.model.person.PersonId;
import com.enn.demo.core.domain.repository.PersonRepository;
import com.enn.demo.core.domain.repository.converter.PersonConverter;
import com.enn.demo.core.domain.util.mybatis.Query;
import com.enn.demo.dal.entity.SysPersonDO;
import com.enn.demo.dal.mapper.SysPersonMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Repository;

import java.util.Map;

/**
 * @author kll
 * @date 2021/5/14
 */
@Repository
public class PersonRepositoryImpl extends ServiceImpl<SysPersonMapper, SysPersonDO> implements PersonRepository, IService<SysPersonDO> {

    @Override
    public IPage<SysPersonDO> queryPage(Map<String, Object> params) {
        return this.baseMapper.queryPage(new Query().getPage(params),params);
    }

    @Override
    public IPage<SysPersonDO> selectPage(Map<String, Object> params) {
        String userName = (String)params.get("userName");
        IPage<SysPersonDO> page = this.baseMapper.selectPage(
                new Query<SysPersonDO>().getPage(params),
                new QueryWrapper<SysPersonDO>().likeRight(StringUtils.isNotBlank(userName),"user_name", userName)
        );
        return page;
    }

    @Override
    public Person find(PersonId personId) {
        SysPersonDO sysPersonDO = this.getById(personId.getId());
        return PersonConverter.toPerson(sysPersonDO);
    }

    @Override
    public void remove(PersonId personId) {
        SysPersonDO sysPersonDO = this.getById(personId.getId());
        sysPersonDO.setDelFlag(DelFlagEnum.DELETED.getValue());
        this.removeById(sysPersonDO);
    }

    @Override
    public PersonId store(Person person) {
        //保存或更新
        SysPersonDO sysPersonDO = PersonConverter.fromPerson(person);
        this.saveOrUpdate(sysPersonDO);
        return new PersonId(sysPersonDO.getId());
    }

}
